<template>
	<view>
		<!-- 空盒子用来防止消息过少时 拉起键盘会遮盖消息 -->
		<view :animation="anData" style="height:10px;"></view>
		<!--滚动区域-->
		<scroll-view scroll-with-animation scroll-y="true" @touchmove="hideKey" style="color: #8c8c8c;" 
			:style="{'height':srcollHeight}" :scroll-top="scrollTop">
			<view id="chat-wraper" scroll-with-animation>
				<view style="display: flex;flex-direction: column; align-content: center;"
					v-for="(item,index) in messages" :key="index">
					<!--机器人回复-->
					<view v-if="item.sender=='ai'"
						style="display: flex;flex-direction: column; align-items: start; padding-bottom: 10px; padding-left: 10px;">
						<view style="display: flex;height: 35px; line-height:35px;">
							<view><u-image width="30" height="30" src="@/static/logo.png"></u-image></view>
							<text>耒耜AI小助手</text>
						</view>
						<view
							style="display: flex; flex-direction: column;  background: #fafafa;border-radius: 8px; margin-right: 10px; box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.05);">
							<view style="padding: 17rpx 20rpx;">
								<u-parse :content="item.content" v-if="item.waiting==0"></u-parse>
								<u-loading-icon textSize="18" v-if="item.waiting==1"
									style="width: 40px;"></u-loading-icon>
							</view>
							<!--消息底部功能按钮-->
							<view style="margin: 5px; display: flex;justify-content:flex-end;" v-if="item.waiting==0">
								<u-icon @click="copyContent(item.content)" name="order" color="#cfcfd1"
									size="22"></u-icon>
							</view>
						</view>
					</view>

					<!--自己发送的问题-->
					<view v-if="item.sender==='user'" style="display: flex; justify-content: flex-end; margin: 5px 10px;">
						<view style="background-color: #409EFF; border-radius: 8px; box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.05);">
							<view style="padding: 17rpx 20rpx; color: #f1f1f1;">
								<text style="word-break: break-all;">{{item.content}}</text>
							</view>
						</view>
					
						<view
							style="border-radius: 50px; width: 35px; height:35px;margin-top: 5px; margin-left: 10px;">
							<u-image width="30" height="30" src="@/static/user.png"></u-image>
						</view>
					</view>
 				</view>
			</view>

			<!-- 防止消息底部被遮 -->
			<view style="height: 120px; background-color: #8c8c8c;">dd </view>
		</scroll-view>

		<!--底部输入框-->
		<view :style="'padding-bottom:'+keyboardHeight+'px'" style="position: fixed;bottom:0px; background-color: #ff0101; height: 120rpx;" >
			<view style="background-color: #FFF; width: 750rpx; display: flex;padding: 10px 20px;flex-direction: row;">
				<view>
					音频
				</view>
				<view style="flex:1 ">
					<u--input style="width: 100%;" :adjustPosition="false" v-model="inputMsg" placeholder="请输入内容" border="surround"></u--input>
				</view>
				<view style="padding: 5px 5px;width:60rpx; border: 1px solid #ff0101; " >
					<u-icon name="plus-circle" size="25"></u-icon>
				</view>
				<view style="padding: 5px 5px;width:60px;" @click="handleSendText">
					<u-icon custom-prefix="custom-icon-send custom-icon" size="25" :color="message==''? '#d6d6d6':'#000000'" ></u-icon>
				</view>
			</view>
		</view>


		<view class="chat-content-wraper" v-if="false">
			<scroll-view :scroll-y="true">
				<view style="flex: 1;">
					<view v-for="(item,index) in messages" :key="index"
						:style="{'padding-bottom':messages.length-1===index?'2rem':'none'}">
						<view v-if="item.sender=='ai'" class="chat-message-ai">
							<!--头像-->
							<view style="display: flex; line-height: 35px;height:35px;">
								<u-image src="/static/logo.png" width="30px" height="30px"></u-image>
								<text>耒耜AI小助手</text>
							</view>
							<view v-if="item.waiting==1" class="content-wraper-ai">
								<u-loading-icon textSize="18" v-if="item.waiting==1"
									style="width: 40px;"></u-loading-icon>
							</view>
							<view class="content-wraper-ai" v-if="item.waiting==0">
								<u-parse :content="item.content"></u-parse>
							</view>
						</view>

						<view v-if="item.sender=='me'" class="chat-message-me">
							<!--头像-->
							<view class="content-wraper-me">
								<rich-text :nodes="item.content"></rich-text>
							</view>
						</view>

					</view>
				</view>
			</scroll-view>

			<!--历史会话-->
			<u-popup :show="historyVisible" mode="left" @close="closeHistory" closeable>
				<view style="display: flex; width:300px;">
					<view style="font-size: 14px; line-height: 40px; flex:1; text-align: center;padding-right:5px">历史会话
					</view>
				</view>
				<view class="history-wraper">
					<view style="padding: 0px 20px; overflow-y: auto;">
						<view style="margin-bottom: 20px;">
							<view class="history_section">今天</view>
							<view style="background-color: #FFF; border-radius: 5px;  padding: 2px 5px;">
								<view style="margin-bottom: 10px;" v-for="(item,index) in history.today" :key="index"
									@click="handleViewHistory(item)">
									<view style="color: #8c8c8c;">{{item.content}}</view>
								</view>
							</view>
						</view>
						<view>
							<view class="history_section">昨天</view>
							<view style="background-color: #FFF; border-radius: 5px;  padding: 2px 5px;">
								<view style="margin-bottom: 10px;" v-for="(item,index) in history.yesterday"
									:key="index" @click="handleViewHistory(item)">
									<view style="color: #8c8c8c;">{{item.content}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</u-popup>
		</view>


		<view class="footer-wraper"  v-if="false">
			<chatInput @send="handleSendText" @openHistory="openHistory"></chatInput>
		</view>


	</view>
</template>

<script>
	import chatInput from '@/components/chatInput.vue'
	export default {
		components: {
			chatInput
		},
		onLoad(option) {
			
			uni.onKeyboardHeightChange(res => {
				console.log(' 跳动',res);
				this.keyboardHeight=res.height;
				const query = uni.createSelectorQuery()
				query.select('#chat-wraper').boundingClientRect(data => {
					
					// 若消息体没有超过2倍的键盘则向下移动差值,防止遮住消息体
					var up = res.height * 2 - data.height - this.aspectRatio * 200
					if (up > 0) {
						// 动态改变空盒子高度
						this.msgMove(up, 300)
						// 记录改变的值,若不收回键盘且发送了消息用来防止消息过多被遮盖
						this.mgUpHeight = up
					}
					// 收回
					if (res.height == 0) {
						this.msgMove(0, 0)
					}
				}).exec();
			})
			
			
			//获取设备屏幕高度
			var query = uni.getSystemInfoSync()
			console.log(query);
			this.aspectRatio = query.screenWidth / 750
			this.windowHeight = query.windowHeight;
			this.srcollHeight = query.windowHeight + "px";
 
			if (option.type == "new") { //创建新会话
				this.chat(option.q, true);
			} else if (option.type == "history") {
				this.messages = [];
				this.messages.push({
					sender: 'me',
					content: option.content
				});
				this.messages.push({
					sender: 'ai',
					waiting: 0,
					content: option.response
				});
				this.historyVisible = false;
			}




		},
		data() {
			return {
				mgUpHeight:0,
				inputMsg:'',
				anData: {},
				animationData: {},
				aspectRatio: 1,
				windowHeight: 0,
				keyboardHeight:0,
				scrollTop: 0,
				srcollHeight: 0,
				isWaiting: false,
				historyVisible: false,
				history: {
					today: [],
					yesterday: []
				},
				messages: [{
						sender: 'ai',
						content: 'Hi，我是耒耜，很高兴认识你！<br/>应用商店搜索“耒耜大模型”随时和我聊天！',
						waiting: 0
					},
					{
						sender: "user",
						content: "你好,你数学觉得怎么样?",
						waiting: 0
					},
					{
						sender: "ai",
						content: "你好，我是最牛逼的机器人,有什么您可以问我。",
						waiting: 0
					},
					{
						sender: "user",
						content: "你好,你数学觉得怎么样?",
						waiting: 0
					},
					{
						sender: "ai",
						content: "你好，我是最牛逼的机器人,有什么您可以问我。",
						waiting: 0
					},
					{
						sender: "user",
						content: "你好,你数学觉得怎么样?",
						waiting: 0
					},
					{
						sender: "ai",
						content: "作为AI助手，我没有实际的感知能力或学习知识的能力。但我可以为您提供解答和帮助您解决问题。如果您有任何问题或需要了解的信息，请随时告诉我！",
						waiting: 0
					},
					{
						sender: "user",
						content: "你好,你数学觉得怎么样?",
						waiting: 0
					},
					{
						sender: "ai",
						content: "你好！很高兴能与你交流。有什么问题或需要帮助的吗？我会尽力提供有益的信息和解答。",
						waiting: 0
					},
					{
						sender: "user",
						content: "你好,你数学觉得怎么样?",
						waiting: 0
					},
					{
						sender: "ai",
						content: "你好，我是最牛逼的机器人,有什么您可以问我。",
						waiting: 0
					}
				]
			}
		},
		methods: {
			//复制
			copyContent(msg) {
				uni.setClipboardData({
					data: msg
				});
			},
			hideKey() {
				uni.hideKeyboard();
			},
			generate(msg = '') {
				// 创建新会话
				this.api.generate({
					prompt: msg
				}).then(lres => {
					if (lres.code == 1) {
						this.isWaiting = false;
						this.messages[this.messages.length - 1].waiting = 0;
						this.messages[this.messages.length - 1].content = lres.response.response;
					}
				});
			},
			chat(msg = "", newchat = false) {

			},
			handleViewHistory(item) {
				this.messages = [];
				this.messages.push({
					sender: 'user',
					content: item.content
				});
				this.messages.push({
					sender: 'ai',
					waiting: 0,
					content: item.response
				});
				this.historyVisible = false;
			},
 			autoScroll(){
				const query = uni.createSelectorQuery()
				// 延时100ms保证是最新的高度
				setTimeout(() => {
					// 获取消息体高度
					query.select('#chat-wraper').boundingClientRect(data => {
						console.log("获取数据",data);
						// 如果超过scorll高度就滚动scorll
						if (data.height - this.windowHeight > 0) {
							this.scrollTop = data.height - this.windowHeight
						}
						console.log(this.scrollTop)
						// 保证键盘第一次拉起时消息体能保持可见
						var moveY = this.windowHeight - data.height + 120;
						// 超出页面则缩回空盒子
						if (moveY - this.mgUpHeight < 0) {
							// 小于0则视为0
							if (moveY < 0) {
								this.msgMove(0, 300)
							} else {
								// 否则缩回盒子对应的高度
								this.msgMove(moveY, 300)
							}
						}
				
					}).exec();
				}, 100)
			},
			// 移动顶部的空盒子
			msgMove(x, t) {
				var animation = uni.createAnimation({
					duration: t,
					timingFunction: 'linear',
				})
			
				this.animation = animation
			
				animation.height(x).step()
			
				this.anData = animation.export()
			},
			handleSendText() {
				if (this.inputMsg.trim() == "") {
					return;
				}
				this.messages.push({
					sender:"user",
					waiting:0,
					content:this.inputMsg
				})
				
		
				this.waitingForResponse(this.inputMsg)
				this.inputMsg="";
				this.autoScroll();
			},
			waitingForResponse(msg){
				// 创建新会话
				this.messages.push({
					sender: 'ai',
					waiting: 1,
					content: ''
				});
				this.isWaiting = true;
				this.api.chat({
					newchat: false,
					content: msg,
				}).then(lres => {
					if (lres.code == 1) {
						this.isWaiting = false;
						this.messages[this.messages.length - 1].waiting = 0;
						this.messages[this.messages.length - 1].content = lres.response;
						this.autoScroll();
					}
				});
			}
			
			,
			/* 历史记录相关*/
			closeHistory() {
				this.historyVisible = false;
			},
			openHistory: function() {
				this.historyVisible = true;
				this.api.get_history_list({}).then(res => {
					this.history = res.data;
				})
			},

		}
	}
</script>

<style scoped>
	.chat-message-me {
		display: flex;
		padding-right: 1rem;
		padding-top: 1rem;
		flex-direction: row-reverse;

	}

	.scroll-view {}

	.chat-message-ai {
		clear: both;
		display: flex;
		flex-direction: column;

		padding-left: 1rem;
		padding-right: 1rem;
		padding-top: 1rem;
		margin-bottom: 1px;
		align-items: left;
		left: 0px;
		right: 0px;
	}

	.content-wraper-ai {
		padding-left: 1rem;
		background-color: #f1f1f1;
		padding: 10px;
		text-align: left;
		border-radius: 0px 10px 10px 10px;
	}

	.chat-content-wraper {
		border: 1px solid #ffffff;
		flex: 1;
		overflow: auto;
		padding-bottom: 30px;
	}

	.content-wraper-me {
		padding-left: 1rem;
		background-color: #0097e3;
		padding: 10px;
		color: #f1f1f1;
		border-radius: 10px 10px 0px 10px;
	}

	.footer-wraper {
		border: 1px solid #ffffff;
		position: sticky;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		color: #fff;
		text-align: center;
	}

	/*历史会话相关样式*/
	.history-wraper {
		background-color: #fafafa;
		overflow-y: auto;
		height: 100vh;
	}

	.history_section {
		line-height: 30px;
		height: 30px;
		padding-left: 5px;
		font-weight: bold;
	}
</style>